package com.jsgt.greekfire.ui.home.entrance.addwallet

import android.text.Editable
import android.text.Selection
import android.text.TextUtils
import android.text.TextWatcher
import android.text.method.HideReturnsTransformationMethod
import android.text.method.PasswordTransformationMethod
import android.view.View
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.fhx.core.goToActivity
import com.fhx.core.utils.ActivityStackManager
import com.fhx.core.utils.StringUtil
import com.fhx.core.utils.ToastUtils
import com.jsgt.greekfire.R
import com.jsgt.greekfire.base.BaseBackgroundActivity
import com.jsgt.greekfire.bean.YTWallet
import com.jsgt.greekfire.common.util.YTWalletUtils
import com.jsgt.greekfire.dao.model.IdentityBean
import com.jsgt.greekfire.dao.model.WalletBean
import com.jsgt.greekfire.dao.viewmodel.WalletViewModel
import com.jsgt.greekfire.ui.main.MainAtrActivity
import kotlinx.android.synthetic.main.activity_login_wallet.*
import org.web3j.crypto.MnemonicUtils


/**
 * 导入钱包
 */
class LoginWalletActivity : BaseBackgroundActivity() {
    private val walletViewModel: WalletViewModel by lazy {
        ViewModelProvider(this).get(WalletViewModel::class.java)
    }

    private var wallet: YTWallet? = null
    override fun getLayoutId(): Int = R.layout.activity_login_wallet
    private var isAdding = false

    override fun onBackPressed() {
        super.onBackPressed()
        overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
    }

    override fun main() {
//        title = getString(R.string.wallet_add)

        cb_eye.setOnCheckedChangeListener { _, isChecked ->
            security_pwd_et.transformationMethod = if (isChecked) {
                HideReturnsTransformationMethod.getInstance()
            } else {
                PasswordTransformationMethod.getInstance();
            }
            if (!security_pwd_et.text.isNullOrEmpty()) {
                Selection.setSelection(security_pwd_et.text, security_pwd_et.text!!.length)
            }
        }

        help_word_et.addTextChangedListener(object : TextWatcher {
            private var index = 0
            override fun afterTextChanged(s: Editable?) {

            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                if (TextUtils.isEmpty(s)) {
                    help_word_error.visibility = View.GONE
                } else {
                    index = 0
                    StringUtil.multiBlankTo1Space(s.toString())!!.split(" ").reversed()
                        .forEach {
                            if (!MnemonicUtils.getWords().contains(it) &&
                                !(index == 0 && (it.isEmpty() || it.length == 1))
                            ) {
                                help_word_error.visibility = View.VISIBLE
                                help_word_error.text =
                                    String.format(getString(R.string.input_help_word_tips1), it)
                                return@onTextChanged
                            }
                            index++
                        }
                    help_word_error.visibility = View.GONE
                }

            }
        })

        start_add_tv.setOnClickListener {
            start_add_tv.isEnabled = false
            showProgress(true)
            val walletName = wallet_name_et.text.toString().trim()
            val securityPwd = security_pwd_et.text.toString().trim()
            val helpWord = StringUtil.multiBlankTo1Space(help_word_et.text.toString().trim())!!
            if (TextUtils.isEmpty(walletName)
                || TextUtils.isEmpty(securityPwd)
                || TextUtils.isEmpty(helpWord)
            ) {
                ToastUtils.show(getString(R.string.input_all_info))
                showProgress(false)
                start_add_tv.isEnabled = true
            } else if (securityPwd.length < 6) {
                ToastUtils.show(getString(R.string.wallet_safe_pwd_warning))
                showProgress(false)
                start_add_tv.isEnabled = true
            } else if (!MnemonicUtils.validateMnemonic(helpWord)) {
                ToastUtils.show(getString(R.string.input_help_word_error))
                showProgress(false)
                start_add_tv.isEnabled = true
            } else {
                try {
                    wallet = YTWalletUtils.generateBip44Wallet(helpWord, securityPwd)
                    if (wallet == null) {
                        showProgress(false)
                        ToastUtils.show(this, getString(R.string.input_help_word_error))
                        start_add_tv.isEnabled = true
                    } else {
                        val identityBean = IdentityBean()
                        identityBean.setMnemonicByAES(helpWord)
                        identityBean.setPriKeyByAES(wallet!!.getEcKeyPair().privateKey.toString())
                        identityBean.setPasswordByMd5(securityPwd)
                        identityBean.identityName = walletName
                        identityBean.backup = true
                        walletViewModel.addIdentity(identityBean)
                    }
                } catch (e: Exception) {
                    showProgress(false)
                    ToastUtils.show(this, getString(R.string.input_help_word_error))
                    start_add_tv.isEnabled = true
                }
            }

            walletViewModel.getAllIdentity()?.observe(this, Observer {
                if (it != null && wallet != null && !isAdding) {
                    it.forEach {it1->
                        if (it1.getPriKeyByAES() == wallet!!.getEcKeyPair().privateKey.toString()) {
                            val walletBean = WalletBean()
                            walletBean.key = "ATR"
                            walletBean.identityId = it1.id
                            walletBean.address = wallet!!.address
                            walletBean.name = "ATR"
                            walletViewModel.addWallet(walletBean)
                            isAdding = true
                            return@Observer
                        }
                    }
                }
                start_add_tv.isEnabled = true
                showProgress(false)
            })

            walletViewModel.getAllWallet()?.observe(this, Observer {
                if (it != null && wallet != null) {
                    it.forEach {it1->
                        if (it1.address == wallet!!.address) {
                            goToActivity<MainAtrActivity>()
                            ActivityStackManager.finishAll()
                            return@Observer
                        }
                    }
                }
                start_add_tv.isEnabled = true
                showProgress(false)
            })
        }
    }
}